#!/bin/sh

Green="\033[32m"
Red="\033[31m"
Yellow='\033[33m'
Font="\033[0m"
INFO="[${Green}INFO${Font}]"
ERROR="[${Red}ERROR${Font}]"
WARN="[${Yellow}WARN${Font}]"

DEFAULT_ARGS="--local-media /media --report --localdb /media"

INFO() {
    echo -e "${INFO} ${1}"
}

ERROR() {
    echo -e "${ERROR} ${1}"
}

WARN() {
    echo -e "${WARN} ${1}"
}

get_loop_device() {
    local img_file="$1"
    local offset="${2:-10000000}"
    
    local mount_dir
    local state_file_dir
    if [ "$img_file" = "media.img" ] || [ "$img_file" = "media_jf.img" ]; then
        mount_dir="/volume_img"
        state_file_dir="/volume_img/xiaoya"
    else
        return 1
    fi
    
    existing_loop=$(losetup -a | grep " $offset" | grep "/$img_file" | head -n1)
    
    if [ -z "$existing_loop" ]; then
        existing_loop=$(losetup -a | grep " $offset" | grep " (/)" | head -n1)
    fi
    
    if [ -n "$existing_loop" ]; then
        found_device=$(echo "$existing_loop" | cut -d: -f1)
        
        if mount "$found_device" "$mount_dir" 2>/dev/null; then
            if [ -f "$state_file_dir/.loop" ]; then
                existing_path=$(cat "$state_file_dir/.loop" | cut -d' ' -f2-)
                
                current_path=$(cat /proc/self/mountinfo | grep -o "\/.*\.img /$img_file" | cut -d' ' -f1)
                
                if [ "$existing_path" = "$current_path" ]; then
                    return 0
                else
                    umount -l "$found_device"
                fi
            else
                umount -l "$found_device"
            fi
        fi
    fi
    
    new_loop=$(losetup -f)
    
    if [ -n "$new_loop" ] && [ ! -e "$new_loop" ]; then
        loop_num=$(echo "$new_loop" | grep -o '[0-9]\+$')
        if ! mknod "$new_loop" b 7 "$loop_num" 2>/dev/null; then
            return 1
        fi
    elif [ -z "$new_loop" ]; then
        return 1
    fi
    
    if losetup -o "$offset" "$new_loop" "/$img_file"; then
        if mount "$new_loop" "$mount_dir"; then
            mkdir -p "$state_file_dir"
            current_path=$(cat /proc/self/mountinfo | grep -o "\/.*\.img /$img_file" | cut -d' ' -f1)
            echo "$new_loop $current_path" > "$state_file_dir/.loop"
            return 0
        else
            losetup -d "$new_loop"
            rm -f "$new_loop" 2>/dev/null
            return 1
        fi
    else
        losetup -d "$new_loop" 2>/dev/null
        rm -f "$new_loop" 2>/dev/null
        return 1
    fi
}

mount_img() {
    local img_file
    if [ "$MODE" = "jellyfin" ]; then
        img_file="media_jf.img"
    else
        img_file="media.img"
    fi
    
    if [ ! -d /volume_img ]; then
        mkdir -p /volume_img
    fi
    
    if [ -d /media ]; then
        if [ ! -d "/media/电影/豆瓣 top 1000部" ]; then
            if ! rm -rf /media; then
                ERROR '删除 /media 失败！使用老G速装版emby请勿将任何目录挂载到容器的 /media 目录！程序退出！'
                exit 1
            fi
        else
            ERROR '/media 文件夹不为空！使用老G速装版emby请勿将任何目录挂载到容器的 /media 目录！程序退出！'
            exit 1
        fi
    fi
    
    if ! get_loop_device "$img_file"; then
        ERROR "$img_file loop设备绑定或挂载失败，程序退出！"
        exit 1
    fi
    
    INFO "媒体库img镜像挂载成功！"
    
    ln -sf /volume_img/xiaoya /media
    if [ -L "/volume_img/xiaoya/xiaoya" ]; then
        rm -f "/volume_img/xiaoya/xiaoya"
    fi
    INFO "/media 创建软链接成功！"
}

MODE=${MODE:-emby}

if [ "$MODE" = "jellyfin" ]; then
    img_file="/media_jf.img"
else
    img_file="/media.img"
fi

if [ -f "$img_file" ]; then
    mount_img
fi

if [ ! -f /bin/user/sync_xy ]; then
    ERROR "sync_xy程序不存在，退出！"
    exit 1
fi

CYCLE=${CYCLE:-24}

has_local_media=0
has_report=0
has_localdb=0

for arg in "$@"; do
    case "$arg" in
        --local-media)
            has_local_media=1
            ;;
        --report)
            has_report=1
            ;;
        --localdb)
            has_localdb=1
            ;;
    esac
done

FINAL_ARGS=""

if [ $# -eq 0 ]; then
    FINAL_ARGS="$DEFAULT_ARGS"
else
    FINAL_ARGS="$@"
    if [ $has_local_media -eq 0 ]; then
        FINAL_ARGS="$FINAL_ARGS --local-media /media"
    fi
    if [ $has_report -eq 0 ]; then
        FINAL_ARGS="$FINAL_ARGS --report"
    fi
    if [ $has_localdb -eq 0 ]; then
        FINAL_ARGS="$FINAL_ARGS --localdb /media"
    fi
fi

if [ "${CYCLE}" -lt 12 ]; then
    WARN "您设置的循环时间小于12h，对于服务器压力过大，同步下载将不会运行！"
    tail -f /dev/null
else
    while true; do
        /bin/user/sync_xy $FINAL_ARGS
        
        TOTAL_SECONDS=$((CYCLE * 3600))
        START_TIME=$(date +%s)
        END_TIME=$((START_TIME + TOTAL_SECONDS))

        if [ -f /xy_sync_ver.txt ]; then
            VERSION=$(cat /xy_sync_ver.txt)
            INFO "当前G-BOX小雅Emby同步工具版本：${VERSION}"
        fi
        
        INFO "当前同步周期为${CYCLE}小时，开始倒计时..."
        
        LOG_INTERVAL=3600
        NEXT_LOG_TIME=$(($(date +%s) + LOG_INTERVAL))
        
        while [ $(date +%s) -lt $END_TIME ]; do
            NOW=$(date +%s)
            REMAINING=$((END_TIME - NOW))
            
            NEXT_EVENT_TIME=$END_TIME
            if [ $NEXT_LOG_TIME -lt $NEXT_EVENT_TIME ]; then
                NEXT_EVENT_TIME=$NEXT_LOG_TIME
            fi
            
            WAIT_TIME=$((NEXT_EVENT_TIME - NOW))
            if [ $WAIT_TIME -lt 1 ]; then
                WAIT_TIME=1
            fi
            
            sleep $WAIT_TIME
            
            NOW=$(date +%s)
            if [ $NOW -ge $NEXT_LOG_TIME ]; then
                REMAINING=$((END_TIME - NOW))
                HOURS=$((REMAINING / 3600))
                MINUTES=$(( (REMAINING % 3600) / 60 ))
                SECONDS=$((REMAINING % 60))
                INFO "距离下次同步还剩: ${HOURS}小时${MINUTES}分钟${SECONDS}秒"
                NEXT_LOG_TIME=$((NOW + LOG_INTERVAL))
            fi
        done
    done
fi
